<template>
  <div id="root">
    <div id="login-box">
      <div id="logo-box">
        <img src="@/assets/logo-whole.png" alt="">
      </div>
      <div id="form-box">
        <el-form :model="formModel" :rules="formRules" ref="formRef" status-icon>
          <div id="welcome-div">库赞考试系统管理端</div>
          <el-form-item prop="userId">
            <el-input prefix-icon="el-icon-user" placeholder="请输入账号"
                      v-model.number="formModel.userId"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input prefix-icon="el-icon-lock" show-password placeholder="请输入密码"
                      v-model.trim="formModel.password"></el-input>
          </el-form-item>
          <el-form-item prop="userCode">
            <div id="valid-code-box">
              <el-input prefix-icon="el-icon-s-promotion"
                        aria-required="true"
                        v-model="formModel.userCode"
                        status-icon="el-icon-warning-outline"
              >
              </el-input>
              <div>
                <valid-code ref="validRef" @update:value="getCode"/>
              </div>
            </div>
          </el-form-item>
          <el-form-item>
            <el-button class="sub-btn" type="primary" @click="submit">登录</el-button>
          </el-form-item>
          <div id="jump-box">
            <div class="jump-page">
              还没注册？点我<span @click="$router.push('/register')">注册</span>
            </div>
            <div id="jump-forget-pwd" @click="modifyDialogFormVisible">忘记密码</div>
          </div>
        </el-form>
      </div>
      <reset-password-form></reset-password-form>
    </div>
  </div>
</template>

<script>
import ValidCode from "@/components/ValidCode.vue";
import {commonMixin} from "@/mixin";
import ResetPasswordForm from "@/components/ResetPasswordForm.vue";
import {mapActions} from "vuex";

export default {
  name: "Login",
  components: {
    ValidCode, ResetPasswordForm,
  },
  mixins: [commonMixin],
  data() {
    // 验证码校验
    const validateCode = (rule, value, callback) => {
      if (value.trim() === '') {
        callback(new Error('请输入验证码'));
      } else if (value.toLowerCase() !== this.showedCode) {
        callback(new Error('验证码错误'));
      } else {
        callback();
      }
    };
    return {
      // 显示的验证码
      showedCode: '',
      // 表单收集的数据
      formModel: {
        // 用户输入的验证码
        userCode: '',
        userId: '',
        password: '',
      },
      // 表单输入规则
      formRules: {
        userId: [
          {type: 'number', required: true, message: '请输入账号', trigger: 'blur'},
        ],
        password: [
          {type: 'string', required: true, message: '请输入密码', trigger: 'blur'},
          {min: 5, max: 12, message: '长度为 5 到 12 个字符', trigger: 'blur'},
        ],
        userCode: [
          {validator: validateCode, trigger: 'blur'}
        ],
      },
    }
  },
  computed: {
    // 将表单数据封装成user对象
    user() {
      return {
        userId: this.formModel.userId,
        password: this.formModel.password,
      }
    }
  },
  methods: {
    ...mapActions('login', ['modifyDialogFormVisible']),
    submit() {
      // 我猜validate方法是el-form的方法
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          const url = '/admin/index/sessions';
          this.axios.post(url, this.user).then(resp => {
            if (resp.code === 200) {
              // 响应成功
              this.$message({
                type: "success",
                message: '登录成功',
                center: true,
              });
              // 更新缓存
              this.updateLocalStorageUser(resp.data);
              this.$router.push('/dashboard');
            } else {
              // 响应失败
              this.$message({
                type: "error",
                message: resp.message,
                center: true,
              });
              this.$refs.validRef.refreshCode();
            }
          })
        } else {
          document.getElementById('')
          console.log('输入有误，请检查！');
          return false;
        }
      });
    },
    getCode(code) {
      return this.showedCode = code.toLowerCase();
    }
  },
}
</script>

<style scoped>
#root {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: linear-gradient(to right, cornflowerblue, ghostwhite)
}

#login-box {
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: aliceblue;
  width: 50em;
  height: 25em;
  border-radius: 0.5em;
}

#logo-box {
  flex: 1;
  margin-left: 1em;

  img {
    width: 100%;
  }
}

#form-box {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
}

.el-form {
  width: 80%;
  height: 100%;
}

#welcome-div {
  font-size: 1.4em;
  font-weight: bold;
  text-align: center;
  margin-bottom: 1.25em;
}

#valid-code-box {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .el-input {
    flex: 1;
  }

  div {
    text-align: center;
    flex: 1;
    height: 2.5em;
  }
}

.sub-btn {
  width: 100%;
}

#jump-box {
  display: flex;
}

.jump-page {
  flex: 3;

  span {
    color: #409eff;
    cursor: pointer;
  }
}

#jump-forget-pwd {
  flex: 2;
  text-align: right;
  color: #409eff;
  cursor: pointer;
}

</style>